from rest_framework import serializers

from course.models import Category, Course, Teacher, Lession, Chapter
from drf_haystack.serializers import HaystackSerializer
from .search_indexes import CourseIndex


class CategorySer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = [
            'id',
            'name'
        ]


class CourseSer(serializers.ModelSerializer):
    children = CategorySer(many=True)
    class Meta:
        model = Category
        fields = '__all__'


# 查子类的子类的序列化器
class CateSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()

    def get_children(self, obj):
        if obj.children.all():
            return CateSerializer(obj.children.all(), many=True).data
        else:
            return []
    class Meta:
        model = Category
        fields = '__all__'


class CourseSerializer(serializers.ModelSerializer):
    # category = CategorySer()
    class Meta:
        model = Course
        fields = '__all__'


class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = '__all__'


class CourseSerSer(serializers.ModelSerializer):
    teacher = TeacherSerializer()
    class Meta:
        model = Course
        fields = '__all__'


class LessionSer(serializers.ModelSerializer):
    class Meta:
        model = Lession
        fields = '__all__'

class ChapteSer(serializers.ModelSerializer):
    lessions = LessionSer(many=True)
    class Meta:
        model = Chapter
        fields = '__all__'


class CourseSearchSerializer(HaystackSerializer):
    class Meta:
        index_classes = [CourseIndex]#设置索引的模型类
        fields = ['text', 'id', 'name', 'price', 'cover', 'level', 'teacher',"students","discount"]













